package io.gitee.mingbaobaba.security.plugin.jpa.repository;

import io.gitee.mingbaobaba.security.core.repository.SecurityCaptchaRepository;
import io.gitee.mingbaobaba.security.plugin.jpa.entity.SecurityCaptchaEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;

/**
 * <p>jpa存储验证码实现</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/9/21 17:20
 */
public class SecurityCaptchaJpaRepository implements SecurityCaptchaRepository {

    @Autowired
    private SecurityCaptchaServiceRepository securityCaptchaServiceRepository;

    @Override
    public String saveCaptcha(String code, long expiry) {
        String captchaSeqId = UUID.randomUUID().toString();
        SecurityCaptchaEntity securityCaptchaEntity = new SecurityCaptchaEntity();
        securityCaptchaEntity.setCode(MessageFormat.format("{0}-{1}", captchaSeqId, code).toLowerCase());
        securityCaptchaEntity.setCreateTime(LocalDateTime.now());
        securityCaptchaEntity.setExpiryTime(LocalDateTime.now().plusSeconds(expiry));
        return captchaSeqId;
    }

    @Override
    public Boolean validCaptcha(String captchaSeqId, String code) {
        if (StringUtils.isBlank(captchaSeqId) || StringUtils.isBlank(code)) {
            return false;
        }
        String validCode = MessageFormat.format("{0}-{1}", captchaSeqId, code)
                .toLowerCase();
        Optional<SecurityCaptchaEntity> optional = securityCaptchaServiceRepository.findById(validCode);
        if (!optional.isPresent()) {
            return false;
        }
        SecurityCaptchaEntity securityCaptchaEntity = optional.get();
        if (securityCaptchaEntity.getExpiryTime().isBefore(LocalDateTime.now())) {
            return false;
        }
        securityCaptchaServiceRepository.deleteById(validCode);
        return true;
    }
}
